package com.solocredit.finance.ui.user.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.solocredit.finance.R
import com.solocredit.finance.base.adapter.MullaOnItemChildClickListener
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.databinding.ActMullaUserFeedbackBinding
import com.solocredit.finance.databinding.ItemMullaUserFeedbackQuestionTypeBinding
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.user.adapter.MullaUserFeedbackImageAdapter
import com.solocredit.finance.ui.user.impl.MullaUserFeedbackPresenterImpl
import com.solocredit.finance.ui.user.view.IMullaUserFeedbackView
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.imagecovert.ImageConvert
import org.json.JSONObject
import java.io.File


/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/16 13:45
 * @Annotation：意见反馈
 */
class MullaUserFeedbackAct: MvpAct<IMullaUserFeedbackView, MullaUserFeedbackPresenterImpl>(), IMullaUserFeedbackView {

    lateinit var binding: ActMullaUserFeedbackBinding
    //图片列表
    private var imgAdapter: MullaUserFeedbackImageAdapter? = null

    //图片压缩后存储的临时文件
    private var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    companion object {
        private const val INTENT_KEY_STAR_COUNT = "starCount"
        fun start(context: Context, count: String? = "") {
            val intent = Intent(context, MullaUserFeedbackAct::class.java)
            intent.putExtra(INTENT_KEY_STAR_COUNT, count)
            context.startActivity(intent)
        }
    }

    override fun getMullaRootView(): View {
        binding = ActMullaUserFeedbackBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): MullaUserFeedbackPresenterImpl {
        return MullaUserFeedbackPresenterImpl(this)
    }

    @SuppressLint("SetTextI18n")
    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTextTitle(getString(R.string.feedback_title))
        setMullaTextTitleGravity(Gravity.CENTER)
        setMullaBackBtnRes(R.mipmap.mulla_back_black)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)

        initMullaRecyclerView()

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                MullaLog.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    MullaLog.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        //最多只能选三张
                        if (imgAdapter?.itemCount == 3){
                            imgAdapter?.removeItem(0)
                        }
                        val imgObj = JSONObject()
                        imgObj.put("isDefault",false)
                        imgObj.put("imgPath",localPath)
                        imgAdapter?.addLastItem(imgObj)

                        showMullaLoading(isTOuchOut = false, isCancel = true)
                        presenter.uploadMullaImageAction(localPath)
                    }
                }

            } else {
                MullaLog.e("No media selected")
            }
        }
    }

    override fun initMullaListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog("UserFeedback Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"UserFeedback Page")
        }
        rootViewBinding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"UserFeedback Page")
            showMullaLanguageDialog("UserFeedback Page", onSelectCallback = {
            })
        }
        //输入框监听
        binding.editRemark.addTextChangedListener(IRemarkChangeListener)
        binding.editRemark.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.editRemark.text.toString().isNotEmpty()){
                HttpHelper.addMullaEventAction(MullaEventType.FORM.MULLA_FORM_USER_FEEDBACK_DESCRIBE,binding.editRemark.text.toString())
            }
        }

        //提交
        binding.btnSubmit.setOnClickListener {
            //问题类型
            if (getSelectTypeItem() == null){
                showMullaToast(getString(R.string.feedback_please_select_question_type))
                return@setOnClickListener
            }
            val remark = binding.editRemark.text.toString()
            if (remark.isEmpty()){
                showMullaToast(getString(R.string.feedback_remark_title))
                return@setOnClickListener
            }
            showMullaLoading(isTOuchOut = false, isCancel = true)
            val params = JSONObject().addCommonParams().addRandomParams().apply {
//                put("path", ApiService.API_PATH.MULLA_API_FEEDBACK_SUBMIT_PATH)
                put("type",getSelectTypeItem()?.optString("value"))//反馈类型
                put("opinion",remark)//反馈内容
            }
            val imgUrls = getSelectImageUrls()
            if (imgUrls.isNotEmpty()){
                params.put("images",imgUrls)
            }
            val starCount = getStarCount()
            if (starCount.isNotEmpty()){
                params.put("starNum",starCount)//从评价弹窗进入反馈页,需要传星级数量
            }
            presenter.submitMullaFeedbackAction(params)
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_USER_FEEDBACK_SUBMIT)
        }
    }

    override fun initMullaData() {
        presenter.loadQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        imgAdapter?.addFirstItem(imgObj)

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 初始化图片列表
     */
    private fun initMullaRecyclerView() {
        binding.recyclerView.setHasFixedSize(false)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.recyclerView.layoutManager = layoutManager
        imgAdapter = MullaUserFeedbackImageAdapter(binding.recyclerView)
        binding.recyclerView.adapter = imgAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        imgAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { parent, childView, position ->
            imgAdapter?.let {
                val item = it.getItem(position)
                when (childView.id) {
                    R.id.imgRemove -> {//删除
                        if (!item.optBoolean("isDefault")) {
                            it.removeItem(position)

                            //是否需要添加默认图片
                            var isAddDefault = true
                            for (i in 0..<it.itemCount) {
                                if (it.getItem(i).optBoolean("isDefault")) {
                                    isAddDefault = false
                                    break
                                }
                            }
                            if (isAddDefault) {
                                val imgObj = JSONObject()
                                imgObj.put("isDefault", true)
                                it.addFirstItem(imgObj)
                            }
                        }
                    }

                    R.id.addLayout -> {//选择图片
                        if (item.optBoolean("isDefault")) {
                            hasRequestPermissions()
                        }
                    }
                }
            }
        })
    }

    private val IRemarkChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            val textLength = s?.length
        }
    }

    /**
     * 设置问题类型列表
     */
    private fun setQuestionTypeList(){
        binding.flexboxLayout.removeAllViews()
        val typeList = presenter.getTypeList()
        typeList?.let { list ->
            for (i in 0..< list.size) {
                val item = list[i]
                val itemBinding = ItemMullaUserFeedbackQuestionTypeBinding.inflate(layoutInflater)
                itemBinding.textView.text = getString(item.optInt("title"))
                if (item.optBoolean("isSelect")){
                    itemBinding.textView.setTextColor(Color.parseColor("#FF8027FF"))
                    itemBinding.textView.setBackgroundResource(R.drawable.mulla_feedback_type_selected)
                    itemBinding.textView.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                } else {
                    itemBinding.textView.setTextColor(Color.parseColor("#FFA5A5A5"))
                    itemBinding.textView.setBackgroundResource(R.drawable.mulla_radius_frame_ffa5a5a5_12)
                    itemBinding.textView.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
                }
                binding.flexboxLayout.addView(itemBinding.root)
                itemBinding.textView.setOnClickListener {
                    if (item.optBoolean("isSelect")){
//                    item.put("isSelect",false)
//                    setQuestionTypeList()
                        return@setOnClickListener
                    }
                    for (index in 0..< list.size){
                        val obj = list[index]
                        if (index == i){
                            obj.put("isSelect",true)
                            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_USER_FEEDBACK_QUESTION_TYPE,getString(obj.optInt("title")))
                        } else {
                            obj.put("isSelect",false)
                        }
                    }
                    setQuestionTypeList()
                }
            }
        }
    }

    /**
     * 获取选择的问题类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var selectItem: JSONObject? = null
        val typeList = presenter.getTypeList()
        typeList?.let {
            for (i in 0..< it.size){
                val obj = it[i]
                if (obj.optBoolean("isSelect")){
                    selectItem = obj
                    break
                }
            }
        }
        return selectItem
    }

    /**
     * 获取上传的图片链接
     */
    private fun getSelectImageUrls(): String{
        var imgUrls = ""
        imgAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                if (item.optBoolean("isDefault")){
                    continue
                }
                imgUrls = imgUrls + item.optString("imgUrl") + ","
            }
        }
        if (imgUrls.isNotEmpty()){
            imgUrls = imgUrls.substring(0,imgUrls.length - 1)
        }
        return imgUrls
    }

    /**
     * 获取评分数量
     */
    private fun getStarCount(): String {
        intent.extras?.let {
            return it.getString(INTENT_KEY_STAR_COUNT,"")
        }
        return ""
    }

    /**
     * 设置意见反馈问题类型列表
     */
    override fun setSibQuestionTypeList(typeList: ArrayList<JSONObject>) {
        setQuestionTypeList()
    }

    /**
     * 图片上传成功，需要删除临时文件
     */
    override fun showSibUploadImageSuccess(imgUrl: String) {
        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
        imgAdapter?.let {
            val lastItem = it.lastItem as JSONObject
            lastItem.put("imgUrl",imgUrl)
        }
        destinationDirectory?.let {
            if (it.isFile){
                it.delete()
            }
        }
    }

    /**
     * 显示反馈提交成功
     */
    override fun showSibSubmitSuccess() {
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },1000)
    }


    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_USER_FEEDBACK_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_USER_FEEDBACK_END)
    }
}